#include<stdio.h>
#include<string.h>
#include<linux/in.h>
#include<sys/types.h>
#include<sys/socket.h>
#include <sys/stat.h>
#include <unistd.h>

struct FileInfo
{
	unsigned int filesize;
	char filename[256];
};
#define SIZE 1024*20

int main(int argc, char **argv)
{
	if(argc < 3)
	{
		printf("used:filesend ip filepath\n");//home/gec/zl.mkv
		return 0;
	}
	//1.创建套接字
	int sockfd = socket(AF_INET, SOCK_STREAM, 0);
	if(sockfd<0)
	{
		perror("socket fail");
		return -1;
	}

	//2.连接服务器
	struct sockaddr_in srvaddr;
	bzero(&srvaddr, sizeof(srvaddr));
	srvaddr.sin_family = AF_INET;
	srvaddr.sin_port = htons(5678);//服务器端口号
	srvaddr.sin_addr.s_addr = inet_addr(argv[1]);//服务器地址
	int ret = connect(sockfd, (struct sockaddr*)&srvaddr, sizeof(srvaddr));
	if(ret < 0)
	{
		perror("connect fail");
		close(sockfd);
		return -1;
	}

	
	
	//获取文件信息---文件名， 文件大小
	struct FileInfo fileinfo;
	
	struct stat statbuf;
	ret = stat(argv[2], &statbuf); //home/gec/zl.mkv  ---opendir("/home/gec/zl.mkv")
	fileinfo.filesize = statbuf.st_size;
	
	char *p = argv[2];
	char *q = p+strlen(p);
	while(q != p && *q != '/')
	{
		q--;
	}
	
	if(q != p)
		q++;
	
	//文件名 
	strcpy(fileinfo.filename, q);
	
	//发送文件信息
	write(sockfd, &fileinfo, sizeof(fileinfo));
	
	//发送文件内容
	//1.打开文件
	char buffer[SIZE];
	FILE *file = fopen(argv[2], "r");
	if(file == NULL)
	{
		perror("fopen fail");
		return -1;
	}
	
	//2.读取文件内容
	unsigned int sendsize = 0;
	while(1)
	{
		ret = fread(buffer, 1, SIZE, file);
		if(ret <= 0)break; //读完或读失败
		//发送一段
		if(write(sockfd, buffer, ret)<=0)
		{
			perror("send fail");
			break;
		}
		sendsize+=ret;
		
		double pos = (double)sendsize/(double)fileinfo.filesize ;
		pos = pos*100;
		
		printf("send:%2d%%\n\033[1A", (int)pos);
	}
	
	fclose(file);
	close(sockfd);
	
	return 0;
}
